package bid.web;

import bid.dao.AreaDao;
import bid.dao.ProjectDao;
import bid.dao.impl.AreaDaoImpl;
import bid.dao.impl.ProjectDaoImpl;
import bid.entity.Area;
import bid.entity.Page;
import bid.entity.Project;
import bid.util.StringUtils;
import com.alibaba.fastjson2.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * @author oldliu
 * @since 1.0
 */
//项目相关的servlet
@WebServlet(name = "ProjectServlet", value = "*.project")
public class ProjectServlet extends HttpServlet {
    ProjectDao projectDao = new ProjectDaoImpl();
//    Project p =new Project();
//    List<Project> projects =new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        String path = req.getServletPath();
        //System.out.println("This is require path:" + path);//    /add.project
        path = path.substring(1, path.length() - 8);
        //System.out.println("This is action name:" + path);
        if ("add".equals(path)) {
            add(req, resp);
        }else if ("findAddress".equals(path)) {
            findAddress(req, resp);
        } else if ("update".equals(path)) {
            update(req, resp);
        } else if ("del".equals(path)) {
            del(req, resp);
        } else if ("search".equals(path)) {
            search(req, resp);
        } else if ("toAdd".equals(path)) {
            toAdd(req, resp);
        } else if ("toUpdate".equals(path)) {
            toUpdate(req, resp);
        }  else if ("download".equals(path)) {
            download(req, resp);
        }else {
            resp.getWriter().println("这是未知操作");
        }
    }
    private AreaDao areaDao=new AreaDaoImpl();
    //发地址信息给html
    private void findAddress(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String codeid=req.getParameter("codeid");
        if(!StringUtils.isNotBlank(codeid))
            codeid="1";

        List<Area> areas = areaDao.findAreas(codeid, -1);
        resp.getWriter().print(JSON.toJSONString(areas));
    }
    private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        long id = Long.parseLong(req.getParameter("id"));
        Project p = projectDao.get(id);
        req.setAttribute("p", p);
        req.getRequestDispatcher("/WEB-INF/view/project/updateProject.jsp").forward(req, resp);

    }

    //这个用来处理add界面中的下拉框，在project表中暂时没用到
    private void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/view/project/addProject.jsp").forward(req, resp);
    }

    private void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //当id传的空值，我们把它设置为-1
        String projectName = StringUtils.trim(request.getParameter("projectName"));
        String projectCategory = StringUtils.trim(request.getParameter("projectCategory"));
        String isEvaluated = StringUtils.trim(request.getParameter("isEvaluated"));
        String registerAddress = StringUtils.trim(request.getParameter("registerAddress"));
//        Long status = StringUtils.toLong(request.getParameter("registerAddress"),null);
        int pageNo = StringUtils.toInt(request.getParameter("pageNo"), 1);
        int pageSize = Page.PAGESIZE;
        Page<Project> page = projectDao.page(pageNo, pageSize, projectName, projectCategory, isEvaluated,
                registerAddress);

        //>>> projects = projectDao.search(pageNo, pageSize,projectName,projectCategory,isEvaluated,registerAddress);

        Project project2 = new Project();
        project2.setProjectName(projectName);
        project2.setProjectCategory(projectCategory);
        project2.setIsEvaluated(isEvaluated);
        project2.setRegisterAddress(registerAddress);
//        project2.setStatus(status);

        //将传来的五个project属性封装到Project的一个实例对象p上进行传输
        request.setAttribute("project2", project2);


        //将条件查到的所有行放到列表对象projects上

        //page对象中包含pageNo第几页,total总数据数,pageNums总页数,PAGESIZE页面大小
        request.setAttribute("page", page);
        //转发
        request.getRequestDispatcher("/WEB-INF/view/project/projects.jsp").forward(request, response);

    }

    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //PrintWriter out = response.getWriter();
        Project p = new Project();

        //文件上传暂存的目录，默认是 java.io.tmpdir
        DiskFileItemFactory dis = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(dis);
        upload.setHeaderEncoding("utf-8");
        String ad0="",ad1="",ad2="",ad3="",ad4="";//ad4是具体的门牌
        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            for (FileItem f : fileItems) {
                if (f.isFormField()) {
                    //out.print("<p>");
                    //out.print("这是普通表单域：" + f.getFieldName() + ",值是：" + f.getString("utf-8"));
                    switch (f.getFieldName()) {
                        case "id":
                            p.setId(StringUtils.toLong(f.getString("utf-8")));

                            break;
                        case "projectName":
                            p.setProjectName(StringUtils.trim(f.getString("utf-8")));
                            break;
                        case "projectCategory":
                            p.setProjectCategory(f.getString("utf-8"));
                            break;
                        case "professorNum":
                            p.setProfessorNum(StringUtils.toInt(f.getString("utf-8")));
                            break;
                        case "isEvaluated":
                            p.setIsEvaluated(StringUtils.trim(f.getString("utf-8")));
                            break;
                        case "prochaseMode":
                            p.setProchaseMode(StringUtils.trim(f.getString("utf-8")));
                            break;
                        case "departmentId":
                            p.setDepartmentId(StringUtils.toLong(f.getString("utf-8")));
                            break;
                        case "budge":
                            p.setBudget(StringUtils.toDouble(f.getString("utf-8")));
                            break;
                        case "announceDate":
                            p.setAnnounceDate(StringUtils.toDate(f.getString("utf-8")));
                            break;
                        case "openDate":
                            p.setOpenDate(StringUtils.toDate(f.getString("utf-8")));
                            break;
                        case "address0":
                            ad0=(StringUtils.trim(f.getString("utf-8")));
                            break;
                        case "address1":
                           ad1=(StringUtils.trim(f.getString("utf-8")));
                            break;
                        case "address2":
                            ad2=(StringUtils.trim(f.getString("utf-8")));
                            break;
                        case "address3":
                            ad3=(StringUtils.trim(f.getString("utf-8")));
                            break;
                        case "address4":
                            ad4=(StringUtils.trim(f.getString("utf-8")));
                            break;
                        case "dealDate":
                            p.setDealDate(StringUtils.toDate(f.getString("utf-8")));
                            break;
                        case "url":
                            p.setUrl(StringUtils.trim(f.getString("utf-8")));
                            //这个部分在修改项目状态时添加
//                        break;case "dealCompany":p.setDealCompany(StringUtils.trim(f.getString("utf-8")));
//                        break;case "settlePrice":p.setSettlePrice(StringUtils.toDouble(f.getString("utf-8")));
                            break;
                        case "linkMan":
                            p.setLinkMan(StringUtils.trim(f.getString("utf-8")));
                            break;
                        case "mobliePhone":
                            p.setMobliePhone(StringUtils.trim(f.getString("utf-8")));
                            break;
                        case "createBy":
                            p.setCreateBy(StringUtils.trim(f.getString("utf-8")));
                            break;
                        case "createDate":
                            p.setCreateDate(StringUtils.toDate(f.getString("utf-8")));
                            break;
                        case "department":
                            p.setDepartment(StringUtils.trim(f.getString("utf-8")));
                            break;
                        case "updateBy":
                            p.setUpdateBy(StringUtils.trim(f.getString("utf-8")));
                            break;
                        case "updateDate":
                            p.setUpdateDate(StringUtils.toDate(f.getString("utf-8")));
                            break;
                        case "registerTime":
                            p.setRegisterTime(StringUtils.toDate(f.getString("utf-8")));
                            break;
                        case "registerAddress":
                            p.setRegisterAddress(StringUtils.trim(f.getString("utf-8")));
                            break;
                        case "committee":
                            p.setCommittee(StringUtils.toLong(f.getString("utf-8")));
                            break;
                        case "professional":
                            p.setProfessional(StringUtils.trim(f.getString("utf-8")));
                            break;
                        case "status":
                            p.setStatus(StringUtils.toLong(f.getString("utf-8")));
                            break;
                    }
                    continue;
                }
                //Wenjian
                if (f.getSize() < 1) {
                    //out.print("文件没有选！");
                    continue;
                }
                String filename = f.getName();
                //最好换名字，不然会同名覆盖
                //换名字，一定要保持后缀
                String houzhui = filename.substring(filename.lastIndexOf('.'));
                filename = UUID.randomUUID() + houzhui;//新名字
                p.setProjectFilePath(filename);
                String files = request.getServletContext().getRealPath("files");
                File folder = new File(files);
                if (folder.exists())
                    folder.mkdirs();//创建目录
                f.write(new File(folder, filename));
                // out.print("文件名叫 " + filename + ",保存在：" + files);
                // out.print("</p>");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //保存
        //额外处理地址
        String address=ad0+' '+ad1+' '+ad2+' '+ad3+' '+ad4;
        p.setAddress(StringUtils.trim(address));

        int r = projectDao.add(p);
        //response.getWriter().println("add:"+r);
        if (r > 0) {
            response.getWriter().print("<script>alert('新增成功');window.location='search.project';</script>");
            return;
        }
        response.getWriter().print("<script>alert('新增失败');window.history.back();</script>");


//        ServletInputStream in = request.getInputStream();
//        int ch=-1;
//        while ((ch=in.read())!=-1){
//            System.out.print((char) ch);
//        }

        //   System.out.println(request.getParameter("projectName")+"??????>????");
//
//        p.setProjectName(request.getParameter("projectName"));
//        p.setProjectCategory(request.getParameter("projectCategory"));
//        p.setProfessorNum(Integer.parseInt(request.getParameter("professorNum")));
//        p.setIsEvaluated(request.getParameter("isEvaluated"));
//        p.setProchaseMode(request.getParameter("prochaseMode"));
//        p.setDepartmentId(Long.parseLong(request.getParameter("departmentId")));
//        p.setBudget(Double.parseDouble(request.getParameter("budget")));
//        p.setAnnounceDate(StringUtils.toDate(request.getParameter("announceDate")));
//        p.setOpenDate(StringUtils.toDate(request.getParameter("openDate")));
//        p.setAddress(request.getParameter("address"));
//        p.setDealDate(StringUtils.toDate(request.getParameter("dealDate")));
//        p.setUrl(request.getParameter("url"));
//        p.setDealCompany(request.getParameter("dealCompany"));
//        p.setSettlePrice(Double.parseDouble(request.getParameter("settlePrice")));
//        p.setLinkMan(request.getParameter("linkMan"));
//        p.setMobliePhone(request.getParameter("mobliePhone"));
//        p.setProjectFilePath(request.getParameter("projectFilePath"));
//        p.setCreateBy(request.getParameter("createBy"));
//        p.setCreateDate(StringUtils.toDate(request.getParameter("createDate")));
//        p.setDepartment(request.getParameter("department"));
//        p.setUpdateBy(request.getParameter("updateBy"));
//        p.setUpdateDate(StringUtils.toDate(request.getParameter("updateDate")));
//        p.setRegisterTime(StringUtils.toDate(request.getParameter("registerTime")));
//        p.setRegisterAddress(request.getParameter("registerAddress"));
//        p.setCommittee(Long.parseLong(request.getParameter("committee")));
//        p.setProfessional(request.getParameter("professional"));
//        p.setStatus(Long.parseLong(request.getParameter("status")));
//        System.out.println(">>>>>>>>>>>>>>>>>>>>"+p);
//        int r = projectDao.add(p);
//        //response.getWriter().println("add:"+r);
//        if (r > 0) {
//            //response.getWriter().print("<script>alert('新增成功');window.location='search.project';</script>");
//            return;
//        }
//         response.getWriter().print("<script>alert('新增失败');window.history.back();</script>");


        //...
    }
    protected void download(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        long id=StringUtils.toLong(request.getParameter("id"));
        Project p=this.projectDao.get(id);
        //11l222.doc
        String path=p.getProjectFilePath();
        path=request.getServletContext().getRealPath("files")+"/"+path;
        File file = new File(path);
        // 取得文件名。
        String filename = p.getProjectName()+path.substring(path.lastIndexOf('.'));
        // 取得文件的后缀名。

        System.out.println(path+"???????????????????????");
        System.out.println(filename+">>>>>");
        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename,"utf-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }
    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        //response.getWriter().println("--Start updateProject action--");
        Project p = new Project();
        p.setId(Long.parseLong(request.getParameter("id")));
        p.setProjectName(request.getParameter("projectName"));
        p.setProjectCategory(request.getParameter("projectCategory"));
        p.setProfessorNum(Integer.parseInt(request.getParameter("professorNum")));
        p.setIsEvaluated(request.getParameter("isEvaluated"));
        p.setProchaseMode(request.getParameter("prochaseMode"));
        p.setDepartmentId(Long.parseLong(request.getParameter("departmentId")));
        p.setBudget(Double.parseDouble(request.getParameter("budget")));
        p.setAnnounceDate(StringUtils.toDate(request.getParameter("announceDate")));
        p.setOpenDate(StringUtils.toDate(request.getParameter("openDate")));
        p.setAddress(request.getParameter("address"));
        p.setDealDate(StringUtils.toDate(request.getParameter("dealDate")));
        p.setUrl(request.getParameter("url"));
        p.setDealCompany(request.getParameter("dealCompany"));
        p.setSettlePrice(Double.parseDouble(request.getParameter("settlePrice")));
        p.setLinkMan(request.getParameter("linkMan"));
        p.setMobliePhone(request.getParameter("mobliePhone"));
        p.setProjectFilePath(request.getParameter("projectFilePath"));
        p.setCreateBy(request.getParameter("createBy"));
        p.setCreateDate(StringUtils.toDate(request.getParameter("createDate")));
        p.setDepartment(request.getParameter("department"));
        p.setUpdateBy(request.getParameter("updateBy"));
        p.setUpdateDate(StringUtils.toDate(request.getParameter("updateDate")));
        p.setRegisterTime(StringUtils.toDate(request.getParameter("registerTime")));
        p.setRegisterAddress(request.getParameter("registerAddress"));
        //这个是Long，要注意
        p.setCommittee(Long.parseLong(request.getParameter("committee")));
        p.setProfessional(request.getParameter("professional"));
        p.setStatus(Long.parseLong(request.getParameter("status")));
        int r = projectDao.update(p);

        if (r > 0) {
            response.getWriter().print("<script>alert('修改成功');window.location='search.project';</script>");
            return;
        }
        response.getWriter().print("<script>alert('修改失败');window.history.back();</script>");


    }

    protected void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        //response.getWriter().println("--Start delProject action--");
        int r = projectDao.del(Long.parseLong(id));
        //response.getWriter().println("del:"+r);
        if (r > 0) {
            response.getWriter().print("<script>alert('删除成功');window.location='search.project';</script>");
            return;
        }
        response.getWriter().print("<script>alert('删除失败,只有项目状态为待抽签时才能删除');window.history.back();</script>");

    }

}